package com.hezuti.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

public class UrlUtil {
	public static Reader getUrlReader(String url,	//the url
			String encode,							//content encode
			int connectTimeout,						//connect timeout, in milliseconds
			int readTimeout							//read timeout, in milliseconds
			) throws IOException {
		URL myUrl = new URL(url);
		
        HttpURLConnection urlCon = (HttpURLConnection)myUrl.openConnection();
        urlCon.setConnectTimeout(connectTimeout);
        urlCon.setReadTimeout(readTimeout);
        
        return new BufferedReader(new InputStreamReader(urlCon.getInputStream(), encode));
	}
	
	public static String getUrlContent(String url,	//the url
			String encode,							//content encode
			int connectTimeout,						//connect timeout, in milliseconds
			int readTimeout							//read timeout, in milliseconds
			) throws IOException {
		BufferedReader in = (BufferedReader) getUrlReader(url, encode, connectTimeout, readTimeout);
		StringBuffer result = new StringBuffer();
        String line;
        try {
             while((line = in.readLine()) != null) {
                  result.append(line).append("\n");
             }
        } catch(IOException e) {
             throw e;
        } finally {
             if(in != null) {
                  in.close();
             }
        }
        return result.toString();
	}
	
	public static String Url2File(String url, String encode, int connectTimeout, int readTimeout, String path)
		throws IOException {
		String content = null;
		if(false) {//TODO 第一次时访问远程
			//url first
			try {
				content = getUrlContent(url, encode, connectTimeout, readTimeout);
				FileUtil.setFileContent(path, content, encode);
			} catch(IOException e) {
				content = FileUtil.getFileContent(path, encode);
			}
		} else {
			//file first
			try {
				content = FileUtil.getFileContent(path, encode);
			} catch(IOException e) {
				content = getUrlContent(url, encode, connectTimeout, readTimeout);
				FileUtil.setFileContent(path, content, encode);
			}
		}
		return content;
	}
	
	public static void main(String[] argv) {
		try {
			String content = Url2File("http://localhost/r/idx.do", "utf-8", 1000, 2000, "C:/tmp.txt");
			System.out.println(content);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}